import * as memberApi from '../api/member';
import type { MemberLevel, Customer, CustomerGroup } from '../api/member';

// 导出类型，使用export type
export type { MemberLevel, Customer, CustomerGroup };

// 声明LeanCloud API响应类型
declare namespace LeanCloud {
  interface Response<T> {
    results: T[];
    count?: number;
  }

  interface ObjectResponse {
    objectId: string;
    createdAt: string;
    updatedAt?: string;
    [key: string]: any;
  }
}

/**
 * 会员服务类
 */
class MemberService {
  /**
   * 获取会员等级列表
   */
  async getMemberLevels(): Promise<MemberLevel[]> {
    try {
      const response = await memberApi.getMemberLevels() as unknown as LeanCloud.Response<MemberLevel>;
      return response.results || [];
    } catch (error) {
      console.error('获取会员等级列表失败:', error);
      // 如果API不可用，返回模拟数据
      return [
        { level: 'VIP1', name: '普通会员', condition: '注册成为会员', benefits: '生日礼券', gifts: '入会礼包', memberCount: 120, objectId: '1' },
        { level: 'VIP2', name: '银卡会员', condition: '累计消费满1000元', benefits: '9.8折优惠', gifts: '升级礼包', memberCount: 85, objectId: '2' },
        { level: 'VIP3', name: '金卡会员', condition: '累计消费满5000元', benefits: '9.5折优惠', gifts: '升级礼包', memberCount: 45, objectId: '3' },
        { level: 'VIP4', name: '钻石会员', condition: '累计消费满10000元', benefits: '9折优惠', gifts: '升级礼包', memberCount: 20, objectId: '4' }
      ];
    }
  }

  /**
   * 获取会员等级详情
   * @param id 会员等级ID
   */
  async getMemberLevelDetail(id: string): Promise<MemberLevel | null> {
    try {
      const response = await memberApi.getMemberLevelDetail(id) as unknown as MemberLevel;
      return response;
    } catch (error) {
      console.error('获取会员等级详情失败:', error);
      return null;
    }
  }

  /**
   * 创建会员等级
   * @param data 会员等级数据
   */
  async createMemberLevel(data: Omit<MemberLevel, 'objectId' | 'createdAt' | 'updatedAt'>): Promise<MemberLevel> {
    try {
      const response = await memberApi.createMemberLevel(data) as unknown as LeanCloud.ObjectResponse;
      return {
        ...data,
        objectId: response.objectId,
        createdAt: response.createdAt
      };
    } catch (error) {
      console.error('创建会员等级失败:', error);
      // 模拟创建成功
      return {
        ...data,
        objectId: Math.random().toString(36).substring(2, 10)
      };
    }
  }

  /**
   * 更新会员等级
   * @param id 会员等级ID
   * @param data 会员等级数据
   */
  async updateMemberLevel(id: string, data: Partial<MemberLevel>): Promise<boolean> {
    try {
      await memberApi.updateMemberLevel(id, data);
      return true;
    } catch (error) {
      console.error('更新会员等级失败:', error);
      // 模拟更新成功
      return true;
    }
  }

  /**
   * 删除会员等级
   * @param id 会员等级ID
   */
  async deleteMemberLevel(id: string): Promise<boolean> {
    try {
      await memberApi.deleteMemberLevel(id);
      return true;
    } catch (error) {
      console.error('删除会员等级失败:', error);
      // 模拟删除成功
      return true;
    }
  }

  /**
   * 获取客户列表
   * @param params 查询参数
   */
  async getCustomerList(params?: any): Promise<{ data: Customer[], total: number }> {
    try {
      const response = await memberApi.getCustomerList(params) as unknown as LeanCloud.Response<Customer>;
      return {
        data: response.results || [],
        total: response.count || 0
      };
    } catch (error) {
      console.error('获取客户列表失败:', error);
      // 模拟数据
      return {
        data: [],
        total: 0
      };
    }
  }

  /**
   * 创建客户
   * @param data 客户数据
   */
  async createCustomer(data: Omit<Customer, 'objectId' | 'createdAt' | 'updatedAt'>): Promise<Customer> {
    try {
      const response = await memberApi.createCustomer(data) as unknown as LeanCloud.ObjectResponse;
      return {
        ...data,
        objectId: response.objectId,
        createdAt: response.createdAt
      };
    } catch (error) {
      console.error('创建客户失败:', error);
      // 模拟创建成功
      return {
        ...data,
        objectId: Math.random().toString(36).substring(2, 10)
      };
    }
  }

  /**
   * 更新客户
   * @param id 客户ID
   * @param data 客户数据
   */
  async updateCustomer(id: string, data: Partial<Customer>): Promise<boolean> {
    try {
      await memberApi.updateCustomer(id, data);
      return true;
    } catch (error) {
      console.error('更新客户失败:', error);
      // 模拟更新成功
      return true;
    }
  }

  /**
   * 删除客户
   * @param id 客户ID
   */
  async deleteCustomer(id: string): Promise<boolean> {
    try {
      await memberApi.deleteCustomer(id);
      return true;
    } catch (error) {
      console.error('删除客户失败:', error);
      // 模拟删除成功
      return true;
    }
  }

  /**
   * 获取客户分组列表
   */
  async getCustomerGroups(): Promise<CustomerGroup[]> {
    try {
      const response = await memberApi.getCustomerGroups() as unknown as LeanCloud.Response<CustomerGroup>;
      return response.results || [];
    } catch (error) {
      console.error('获取客户分组列表失败:', error);
      // 模拟数据
      return [];
    }
  }

  /**
   * 创建客户分组
   * @param data 分组数据
   */
  async createCustomerGroup(data: Omit<CustomerGroup, 'objectId' | 'createdAt' | 'updatedAt'>): Promise<CustomerGroup> {
    try {
      const response = await memberApi.createCustomerGroup(data) as unknown as LeanCloud.ObjectResponse;
      return {
        ...data,
        objectId: response.objectId,
        createdAt: response.createdAt
      };
    } catch (error) {
      console.error('创建客户分组失败:', error);
      // 模拟创建成功
      return {
        ...data,
        objectId: Math.random().toString(36).substring(2, 10)
      };
    }
  }

  /**
   * 更新客户分组
   * @param id 分组ID
   * @param data 分组数据
   */
  async updateCustomerGroup(id: string, data: Partial<CustomerGroup>): Promise<boolean> {
    try {
      await memberApi.updateCustomerGroup(id, data);
      return true;
    } catch (error) {
      console.error('更新客户分组失败:', error);
      // 模拟更新成功
      return true;
    }
  }

  /**
   * 删除客户分组
   * @param id 分组ID
   */
  async deleteCustomerGroup(id: string): Promise<boolean> {
    try {
      await memberApi.deleteCustomerGroup(id);
      return true;
    } catch (error) {
      console.error('删除客户分组失败:', error);
      // 模拟删除成功
      return true;
    }
  }

  /**
   * 获取分组内的客户列表
   * @param groupId 分组ID
   * @param params 查询参数
   */
  async getCustomersByGroup(groupId: string, params?: any): Promise<{ data: any[], total: number }> {
    try {
      const response = await memberApi.getCustomersByGroup(groupId, params) as unknown as LeanCloud.Response<any>;
      return {
        data: response.results || [],
        total: response.count || 0
      };
    } catch (error) {
      console.error('获取分组内的客户列表失败:', error);
      // 模拟数据
      return {
        data: [],
        total: 0
      };
    }
  }

  /**
   * 将客户添加到分组
   * @param groupId 分组ID
   * @param customerId 客户ID
   */
  async addCustomerToGroup(groupId: string, customerId: string): Promise<boolean> {
    try {
      await memberApi.addCustomerToGroup(groupId, customerId);
      return true;
    } catch (error) {
      console.error('将客户添加到分组失败:', error);
      // 模拟添加成功
      return true;
    }
  }

  /**
   * 将客户从分组中移除
   * @param relationId 关系记录ID
   */
  async removeCustomerFromGroup(relationId: string): Promise<boolean> {
    try {
      await memberApi.removeCustomerFromGroup(relationId);
      return true;
    } catch (error) {
      console.error('将客户从分组中移除失败:', error);
      // 模拟移除成功
      return true;
    }
  }
}

export default new MemberService(); 